<?php

namespace App\Console\Commands;

use App\Models\Forum;
use App\Models\ForumStatistics;
use App\Models\ForumTaxonomy;
use Carbon\Carbon;
use Illuminate\Console\Command;

class StatForum extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stat:forum';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计版块每天发帖情况';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $yesterday = Carbon::yesterday();
        $today = Carbon::today();
        $tomorrow = Carbon::tomorrow();
        $forumTaxonomy = ForumTaxonomy::query()->with(['forums' => function ($query) {$query->orderBy('display_order', 'desc');}])->get();
        foreach ($forumTaxonomy as $taxonomy) {
            foreach ($taxonomy->forums as $forum) {
                //昨日
                $this->countAndInsert($taxonomy, $forum, $yesterday, $today);
                //今日
                $this->countAndInsert($taxonomy, $forum, $today, $tomorrow);
                //历史
                $this->countAndInsert($taxonomy, $forum);
            }
        }

    }

    private function countAndInsert(ForumTaxonomy $taxonomy, Forum $forum, $beginTime = null, $endTime = null)
    {
        $query = $forum->topics();
        if ($beginTime) {
            $query->where('topics.created_at', '>=', $beginTime);
        }
        if ($endTime) {
            $query->where('topics.created_at', '<', $endTime);
        }
        $topicCount = $query->count();

        //@todo 此关联，帖子删除，回复不算。。。
        $query = $forum->comments();
        if ($beginTime) {
            $query->where('comments.created_at', '>=', $beginTime);
        }
        if ($endTime) {
            $query->where('comments.created_at', '<', $endTime);
        }
        $commentCount = $query->count();

        $log = sprintf("%s - %s, 日期：%s， 帖子数：%s, 回复数：%s", $taxonomy->name, $forum->name, $beginTime ? $beginTime->format('Y-m-d') : '未指定', $topicCount, $commentCount);
        if ($beginTime === null && $endTime === null) {
            $forum->update(['topic_count' => $topicCount, 'comment_count' => $commentCount]);
        } else {
            $date = $beginTime->format('Y-m-d');
            $forum->topicStat()->updateOrCreate(['date' => $date], ['value' => $topicCount, 'type' => ForumStatistics::TYPE_TOPIC_EVERYDAY]);
            $forum->commentStat()->updateOrCreate(['date' => $date], ['value' => $commentCount, 'type' => ForumStatistics::TYPE_COMMENT_EVERYDAY]);
        }

        $this->info($log);
    }
}
